package baiqitun.stupro.subject.core.task.impl;

import baiqitun.stupro.common.exception.enums.support.ExistedExceptionEnum;
import baiqitun.stupro.common.exception.enums.support.NotFoundExceptionEnum;
import baiqitun.stupro.common.exception.support.ExistedException;
import baiqitun.stupro.common.exception.support.NotFoundException;
import baiqitun.stupro.common.workflow.util.HistoryUtil;
import baiqitun.stupro.common.workflow.util.RepositoryUtil;
import baiqitun.stupro.security.entity.SysUser;
import baiqitun.stupro.security.service.SysUserService;
import baiqitun.stupro.common.workflow.task.AbstractBooleanServiceTaskHandler;
import baiqitun.stupro.subject.entity.SysStudentInfo;
import baiqitun.stupro.subject.service.SysStudentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 服务任务处理器
 * @author kedaji
 */
@Service("selectTutorServiceTaskHandler")
public class SelectTutorServiceTaskHandler extends AbstractBooleanServiceTaskHandler {
    @Autowired
    private HistoryUtil historyUtil;
    @Autowired
    private RepositoryUtil repositoryUtil;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysStudentInfoService sysStudentInfoService;

    @Transactional(readOnly = true, rollbackFor = Exception.class)
    @Override
    public void handleTrue(DelegateExecution execution) {
        HistoricTaskInstance historicTaskInstance = getHistoricTaskInstance(execution);
        // 查找当前学生信息
        sysUserService.checkNotFound(historicTaskInstance.getOwner(), new NotFoundException(NotFoundExceptionEnum.USER_NOT_FOUND));
        SysStudentInfo queryStudentInfo = new SysStudentInfo();
        queryStudentInfo.setUserId(historicTaskInstance.getOwner());
        SysStudentInfo resultStudentInfo = sysStudentInfoService.getOne(new QueryWrapper<>(queryStudentInfo));
        // 使用学生信息的id 来修改修改学生信息中的tutorId
        SysStudentInfo studentInfo = new SysStudentInfo();
        SysUser user = sysUserService.getById(resultStudentInfo.getUserId());
        studentInfo.setTutorId(historicTaskInstance.getAssignee()).setId(resultStudentInfo.getId()).setUpdateBy(user.getUsername());
        sysStudentInfoService.updateById(studentInfo);
        //TODO 给学生发条消息
    }

    @Transactional(readOnly = true, rollbackFor = Exception.class)
    @Override
    public void handleFalse(DelegateExecution execution) {
        //TODO 给学生发条消息
    }
}
